package com.webas.pages;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.grid.GridDataSource;
import org.apache.tapestry5.hibernate.HibernateGridDataSource;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.webas.api.Application;
import com.webas.dao.SearchCriteria;
import com.webas.entities.SoftwareSite;
/**
 * 
 * @author tkhasano
 *
 */
public class Search
{
    @Inject
    private Session session;

    @InjectComponent
    private Zone result;
    
    @InjectComponent
    private Zone applicationZone;

    @SessionState
    @Property
    private SearchCriteria criteria;

    @Property
    private GridDataSource source = new DataSource(session, SoftwareSite.class);

    @Property
    private GridDataSource applicationSource = new DataSource(session, SoftwareSite.class);

    @Property
    private SoftwareSite softwareSite;
    
    @Property
    private Application currentApplication;

    private final class DataSource extends HibernateGridDataSource
    {
        @SuppressWarnings("rawtypes")
		private DataSource(Session session, Class entityType)
        {
            super(session, entityType);
        }

        @Override
        public int getAvailableRows()
        {
            return criteria.getSearchPattern() == null 
            		? 0
            		: super.getAvailableRows();
        }

        @Override
        protected void applyAdditionalConstraints(Criteria crit)
        {
            crit.add(Restrictions.ilike("name", criteria.getSearchPattern()));
        }
    }

    /**
     * Move this into a hotel query service
     */
    @OnEvent(value = EventConstants.SUCCESS)
    Object searchHotels()
    {
        return applicationZone.getBody();
    }
    
    Object onAction()
    {
        return applicationZone.getBody();
    }

}
